﻿define([
    'domReady!',
    'jquery-confirm',
    'bootstrap-table',
    'bootstrap-table-zh-CN',
    'bootstrap-select',
    'defaults-zh_CN',
    'lyear-loading',
    'validate',
    'validate_config',
    'jquery.ajaxRequest',
], function (domReady) {
    //表单验证
    var v = $("#form").validate({
        rules: {
            account: {
                required: {
                    depends: function () {

                        return !($("#account").val().length > 0 || $("#phone").val().length > 0 || $("#email").val().length > 0)
                    }
                }
            },
            email: {
                required: {
                    depends: function () {
                        return !($("#account").val().length > 0 || $("#phone").val().length > 0 || $("#email").val().length > 0)
                    }
                },
                email: true,
            },
            phone: {
                required: {
                    depends: function () {
                        return !($("#account").val().length > 0 || $("#phone").val().length > 0 || $("#email").val().length > 0)
                    }
                },
                phone: true
            }
        },
        messages: {
            account: {
                required: "账号、手机号或邮箱至少填一个。"
            },
            email: {
                required: "账号、手机号或邮箱至少填一个。",
                email: "请填写正确的邮箱格式。",
            },
            phone: {
                required: "账号、手机号或邮箱至少填一个。",
                phone: "请填写正确的手机号格式。"
            }

        }
    });
    function init() {
        //页面数据绑定
        dataBind();
        }
        /**
         * 
         * @param {any} refresh
         */
    function dataBind(refresh) {
        // table使用
        $('#table').bootstrapTable({
            classes: 'table table-bordered table-hover table-striped',
            url: '/BMS/User/GetUserList',
            method: 'post',
            dataType: 'json',
            uniqueId: 'uid',
            idField: 'uid',
            toolbar: '',
            clickToSelect: false,
            showColumns: false,
            showRefresh: false,
            showToggle: false,
            pagination: true,
            sortOrder: "desc",
            queryParams: function (params) {
                var temp = {
                    limit: params.limit,         // 每页数据量
                    offset: params.offset,       // sql语句起始索引
                    page: (params.offset / params.limit) + 1,
                    sort: 'Uid desc',           // 排序的列名
                    sortOrder: params.order,      // 排序方式'asc' 'desc'
                    searchType: $("#searchType").val(),
                    searchText: $("#searchText").val()
                };
                return temp;
            },
            sidePagination: "server",
            pageNumber: 1,                       // 初始化加载第一页，默认第一页
            pageSize: 25,                        // 每页的记录行数
            pageList: [10, 25, 50, 100],         // 可供选择的每页的行数
            //search: true,                      // 是否显示表格搜索，此搜索是客户端搜索
            //showExport: true,        // 是否显示导出按钮, 导出功能需要导出插件支持(tableexport.min.js)
            //exportDataType: "basic", // 导出数据类型, 'basic':当前页, 'all':所有数据, 'selected':选中的数据
            columns: [{
                field: 'ck',
                checkbox: true    // 是否显示复选框
            }, {
                field: 'uid',
                title: '用户Id',

            }, {
                field: 'portrait',
                title: '头像',
                formatter: function (value, row, index) {
                    var html = "<img class='img-avatar img-avatar-48 m-r-10' src='" + row.portrait + "' />";
                    return html;
                }
            }, {
                field: 'account',
                title: '账号'
            }, {
                field: 'phone',
                title: '手机号'
            }, {
                field: 'nickname',
                title: '昵称'
            }, {
                field: 'email',
                title: '邮箱',
            }, {
                field: 'registTime',
                title: '注册时间'
            },
            {
                field: 'status',
                title: '状态',
                sortable: true,
                formatter: function (value, row, index) {
                    if (value == 1) {
                        is_checked = '';
                    } else if (value == 0) {
                        is_checked = 'checked="checked"';
                    }
                    result = '<div class="custom-control custom-switch"><input type="checkbox" class="custom-control-input" id="customSwitch' + row.uid + '" ' + is_checked + '><label class="custom-control-label role-switch" for="customSwitch' + row.uid + '" ></label></div>';

                    return result;
                },
                events: {
                    'click .role-switch': function (e, value, row, index) {
                        updateStatus(row.id, value);
                    }
                }
            }, {
                field: 'operate',
                title: '操作',
                formatter: function (value, row, index) {
                    var html =
                        '<a href="/BMS/User/UserDetail/'+row.uid+'" class="btn btn-xs btn-info  m-r-5" title="详情" data-toggle="tooltip"><i class="mdi mdi-account-card-details"></i>详情</a>' +
                        '<a href="javascript:void(0)" class="btn btn-xs btn-warning reset-btn  m-r-5" title="重置密码" data-toggle="tooltip"><i class="mdi mdi-lock-reset"></i>重置密码</a>' +
                        '<a href="javascript:void(0)" class="btn btn-xs btn-danger del-btn" title="删除" data-toggle="tooltip"><i class="mdi mdi-window-close"></i>删除</a>';
                    return html;
                },  // 自定义方法
                events: {
                    'click .del-btn': function (event, value, row, index) {
                        var ids = [row.uid];
                        del(ids)
                    },
                    'click .reset-btn': function (event, value, row, index) {
                        resetPwd(row.uid)
                    }
                }
            }],
            onLoadSuccess: function (data) {
            }

        });
    }

    function resetPwd(uid){
        $.confirm({
            title: '操作确认',
            content: '确定要将密码重置为初始密码吗？',
            escapeKey: 'cancelAction',
            buttons: {
                confirm: {
                    btnClass: 'btn-red',
                    text: '是',
                    keys: ['enter'],
                    action: function () {
                        $(this).ajaxRequest("/BMS/User/ResetPassword", { uid: uid },false,false);
                    }
                },
                cancelAction: {
                    text: '再想想',
                    action: function () {

                    }
                }
            }
        });
    }

    /**
     * 删除用户
     * @param {any} ids
     */
    function del(ids) {
        $.confirm({
            title: '操作确认',
            content: '确定要删除吗？',
            escapeKey: 'cancelAction',
            buttons: {
                confirm: {
                    btnClass: 'btn-red',
                    text: '是',
                    keys: ['enter'],
                    action: function () {
                        $(this).ajaxRequest("/BMS/User/Delete", { uids: ids }, function () { $('#table').bootstrapTable('refresh') }, false);
                    }
                },
                cancelAction: {
                    text: '再想想',
                    action: function () {

                    }
                }
            }
        });
    }

    function bind() {
        //搜索按钮事件
        $(document).on("click", "#btnSearch", function () {
            $("#table").bootstrapTable('refresh')
        })
        //新增按钮事件
        $(document).on("click", "#btnAdd", function (event) {
            $("#account").val("");
            $("#phone").val("");
            $("#email").val("");
            $("#addDialogModal").modal("show");

        })

        //模态框的保存事件
        $(document).on("click", "#btnSave", function () {
            if (!v.form()) {
                return;
            }
            $(this).attr('disabled', true);
            $this = $(this)
            var account = $("#account").val();
            var phone = $("#phone").val();
            var email = $("#email").val();
            $(this).ajaxRequest("/BMS/User/Add", { account: account, phone: phone, email: email }, function (data) {
                $('#table').bootstrapTable("refresh")
                $("#addDialogModal").modal("hide");
            }, true, false, function () { $this.attr('disabled', false); });
        })
        //模态框消失事件
        $("#addDialogModal").on("hidden.bs.modal", function (e) {
            $("#btnSave").prop('disabled', false)
        })
        //删除事件
        $(document).on('click', '#btnDel', function () {
            var ids = [];
            $.each($('#table').bootstrapTable('getAllSelections'), function (i, row) {
                ids.push(row.uid);
            });

            del(ids)
        });
    }


    $(document).ready(function () {
        init();
        bind();
    })
});